<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Code;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Validate;
use think\Db;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third', "registCode", "getGameLists", "getGameDetail", "test", "getUserLoginStatus"];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code     验证码
     */
    public function register()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 填写注册码，登录会员/注册会员
     *
     * @ApiMethod (POST)
     */
    public function registCode()
    {
        //注册码
        $regist_code = $this->request->post('regist_code');
        $mobile_id = $this->request->post('mobile_id');
       
        if (!$regist_code || !$mobile_id) {
            $this->error(__('Invalid parameters'));
        }
       
        $ret = Code::check($regist_code);
        if (!$ret) {
            $this->error("注册码错误，登录失败");
        }
 
        //注册码正确，通过设备id查询是否已经是用户了，是用户则登录，不是则注册
        $userRet = $this->auth->getUserInfo_mobileId($mobile_id);

        //用户未注册，先注册，生成用户信息，并登录
        if($userRet == 2){
            $createRet = $this->auth->registCode($mobile_id, "123123");
            if($createRet){
                $data = ['userinfo' => $this->auth->getUserinfo()];
                //用户id补全4位数
                $id_name=sprintf("%04d", $data["userinfo"]["id"]);
                $data["userinfo"]["id_name"] = $id_name;
                //新用户注册默认冻结
                Db::name("user")->where("id = " . $data["userinfo"]["id"])->update(["status" => "hidden"]);

                //今天的开始时间戳
                $today_start = strtotime(Date("Y-m-d 00:00:00"));
                //今天的结束时间
                $today_end = strtotime(Date("Y-m-d 23:59:59"));
                //读取当天已发布的主料数据，和用户进行绑定
                //1澳门
                $zhu_ao_lists = Db::name("game")
                ->where("area_type = 1")
                ->where("`release` = 1")
                ->where("releasetime >= " . $today_start)
                ->where("releasetime <= " . $today_end)
                ->where("type = 2")
                ->select();
                //2香港
                $zhu_hk_lists = Db::name("game")
                ->where("area_type = 2")
                ->where("`release` = 1")
                ->where("releasetime >= " . $today_start)
                ->where("releasetime <= " . $today_end)
                ->where("type = 2")
                ->select();

                if($zhu_ao_lists){
                    foreach($zhu_ao_lists as &$zhu_ao_val){
                        $zhu_ao_info = $zhu_ao_val;
                        $zhu_ao_info["uid"] = $data["userinfo"]["id"];
                        $zhu_ao_info["game_id"] = $zhu_ao_info["id"];
                        unset($zhu_ao_info["id"]);
                        Db::name("game_user")->insert($zhu_ao_info);
                    }
                }
                
                if($zhu_hk_lists){
                    foreach($zhu_hk_lists as &$zhu_hk_val){
                        $zhu_hk_info = $zhu_hk_val;
                        $zhu_hk_info["uid"] = $data["userinfo"]["id"];
                        $zhu_hk_info["game_id"] = $zhu_hk_info["id"];
                        unset($zhu_hk_info["id"]);
                        Db::name("game_user")->insert($zhu_hk_info);
                    }
                }

                $this->success(__('Sign up successful'), $data);
            }else{
                $this->error("注册失败，请联系管理员");
            }
        }

        if($userRet == 3){
            $this->error("账户已冻结，无法访问");
        }
        
        //直接登录
        $loginRet = $this->auth->loginMobileId($mobile_id, "123123");

        if ($loginRet) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            //用户id补全4位数
            $id_name=sprintf("%04d", $data["userinfo"]["id"]);
            $data["userinfo"]["id_name"] = $id_name;
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $bio = $this->request->post('bio');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type", "mobile");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    //判断用户是否存在
    public function getUserLoginStatus()
    {
        //用户
        $uid = $this->request->post("uid", 0);
        if(empty($uid)){
            $this->error("请先登录");
        }

         //判断用户状态
         $userInfo = Db::name("user")
         ->field("createtime, status")
         ->where("id = " . $uid)
         ->find();
         
         if($userInfo["status"] == ""){
             $this->success("用户不存在，请重新登录", ["user_status" => 3]);
         }
 
         if($userInfo["status"] != "normal"){
             $this->success("账户已冻结，无法访问", ["user_status" => 2]);
         }

         $this->success("用户状态正常", ["user_status" => 1]);
    }

    //获取当前活动列表
    public function getGameLists()
    {
        //用户
        $uid = $this->request->post("uid", 0);
        //1澳门 2香港
        $area_type = $this->request->post("area_type", 1);

        if(empty($uid)){
            $this->error("请先登录");
        }

         //判断用户状态
         $userInfo = Db::name("user")
         ->field("createtime, status")
         ->where("id = " . $uid)
         ->find();
         
         if($userInfo["status"] == ""){
             $this->error("用户不存在，请重新登录");
         }
 
         if($userInfo["status"] != "normal"){
             $this->error("账户已冻结，无法访问");
         }

        $game_name_lists = Db::name("game_name")
        ->field("colum, title, name")
        ->where("area_type = " . $area_type)
        ->select();

        foreach($game_name_lists as &$value){
            if($area_type == 1){
                $value["area_name"] = "澳门";
            }
            if($area_type == 2){
                $value["area_name"] = "香港";
            }
            
        }
        
        $this->success("操作成功", $game_name_lists);
    }

    //获取活动详情 区分主料辅料
    public function getGameDetail()
    {
        //用户
        $uid = $this->request->post("uid", 0);
        //地区
        $area_type = $this->request->post("area_type", 0);
        //活动字段
        $colum = $this->request->post("colum", "");
        //期数
        $stage_no = $this->request->post("stage_no", 0);

        if(empty($uid)){
            $this->error("请先登录");
        }

        if(empty($area_type)){
            $this->error("地区参数不能为空");
        }

        if(empty($colum)){
            $this->error("活动参数不能为空");
        }

        //用户注册时间
        $userInfo = Db::name("user")
        ->field("createtime, status, engine")
        ->where("id = " . $uid)
        ->find();
        
        if($userInfo["status"] == ""){
            $this->error("用户不存在，请重新登录");
        }

        if($userInfo["status"] != "normal"){
            $this->error("账户已冻结，无法访问");
        }

        //用户注册日期当天开始时间戳
        $userInfo_createStartTime = strtotime(date("Y-m-d 00:00:00", $userInfo["createtime"]));
        //用户注册日期当天结束时间戳
        $userInfo_createEndTime = strtotime(date("Y-m-d 23:59:59", $userInfo["createtime"]));

        //2主料 1辅料
        $type = 2;
        
        //判断用户是否开启主机开关 开启主机，不需要拼接主料数据，全部读取主料
        if($userInfo["engine"] == 1){
            $count_Game_Fu = 0;
        }else{
            //非主机用户，需要查询注册之后（不包括注册当天），发布了多少期辅料，如果大于10期，直接查询最近10期辅料，小于10期，往前倒序用主料补够10期
            $count_Game_Fu = Db::name("game")
            ->where("area_type = " . $area_type) //地区
            ->where("type = 1") //辅料
            ->where("`release` = 1") //已发布状态
            ->where("releasetime > " . $userInfo_createEndTime) //用户注册日期小于发布日期
            ->count("id");
        }

        if($count_Game_Fu >= 10){
            $type = 1;
            //查询最近10期的辅料期数列表
            $game_stage_ten = Db::name("game")
            ->field("type, stage_name, stage_no")
            ->where("type = " . $type)
            ->where("area_type = " . $area_type)
            ->where("`release` = 1") //已发布状态
            ->order("stage_no desc")
            ->limit(10)
            ->select();
        }else if($count_Game_Fu < 10 && $count_Game_Fu > 0){
            $type = 1;
            $game_stage_Fu = Db::name("game")
            ->field("type, stage_name, stage_no")
            ->where("type = 1")
            ->where("area_type = " . $area_type)
            ->where("`release` = 1") //已发布状态
            ->where("releasetime > " . $userInfo_createEndTime)
            ->order("stage_no desc")
            ->limit($count_Game_Fu)
            ->select();

            $count_Game_Zhu = bcsub(10, $count_Game_Fu);
            $game_stage_Zhu = Db::name("game")
            ->field("type, stage_name, stage_no")
            ->where("type = 2")
            ->where("area_type = " . $area_type)
            ->where("`release` = 1") //已发布状态
            ->where("releasetime <= " . $userInfo_createEndTime)
            ->order("stage_no desc")
            ->limit($count_Game_Zhu)
            ->select();

            $game_stage_ten = array_merge($game_stage_Fu, $game_stage_Zhu);

        }else if($count_Game_Fu == 0 && $userInfo["engine"] == 0){ //非主机用户，只能看到注册日期之前的主料
            $game_stage_ten = Db::name("game")
            ->field("type, stage_name, stage_no")
            ->where("type = 2")
            ->where("area_type = " . $area_type)
            ->where("`release` = 1") //已发布状态
            ->where("releasetime <= " . $userInfo_createEndTime)
            ->order("stage_no desc")
            ->limit(10)
            ->select();
        }else if($count_Game_Fu == 0 && $userInfo["engine"] == 1){//主机用户，可以不限制注册日期 读取主料数据
            $game_stage_ten = Db::name("game")
            ->field("type, stage_name, stage_no")
            ->where("type = 2")
            ->where("area_type = " . $area_type)
            ->where("`release` = 1") //已发布状态
            ->order("stage_no desc")
            ->limit(10)
            ->select();
        }

        //今天的开始时间戳
        $today_start = strtotime(Date("Y-m-d 00:00:00"));
        //今天的结束时间
        $today_end = strtotime(Date("Y-m-d 23:59:59"));

        $game_detail = [];
        //获取活动详情
        if($stage_no == 0){
            $game_detail = Db::name("game")
            ->field($colum . ", zodiac, number, stage_name, stage_no, type")
            ->where("type = " . $type)
            ->where("area_type = " . $area_type)
            ->where("`release` = 1") //已发布状态
            ->order("stage_no desc")
            ->find();

            //查询最新一期, 非主机用户，如果当前是需要读取主料，则判断，是否今天注册的，如果是，则读取用户绑定的主料
            if($type == 2 && $userInfo["engine"] == 0 && $userInfo_createEndTime >= $today_start && $userInfo_createEndTime <= $today_end){
                $game_detail_new = Db::name("game_user")
                ->field($colum . ", zodiac, number, stage_name, stage_no, type")
                ->where("uid = " . $uid)
                ->where("type = " . $type)
                ->where("area_type = " . $area_type)
                ->where("`release` = 1") //已发布状态
                ->order("stage_no desc")
                ->find();
                //如果今天绑定了数据，则覆盖当前数据，否则不覆盖
                if($game_detail_new){
                    $game_detail = $game_detail_new;
                }
            }
            
        }else{
            //主料辅料加在一起的情况
            if($count_Game_Fu < 10 && $count_Game_Fu > 0){
                //查询当前这一期活动 主料 创建时间是否小于等于用户注册时间
                $createtime_compare = Db::name("game")
                ->field("id")
                ->where("type = 2")
                ->where("releasetime <= " . $userInfo_createEndTime)
                ->where("area_type = " . $area_type)
                ->where("`release` = 1") //已发布状态
                ->where("stage_no = " . $stage_no)
                ->find();
                
                if($createtime_compare){
                    $type = 2;
                }else{
                    $type = 1;
                }
            }
            $game_detail = Db::name("game")
            ->field($colum . ", zodiac, number, stage_name, stage_no, type, releasetime")
            ->where("type = " . $type)
            ->where("area_type = " . $area_type)
            ->where("`release` = 1") //已发布状态
            ->where("stage_no = " . $stage_no)
            ->find();

            //查询这一期, 非主机用户情况下，如果当前是需要读取主料，则判断，是否当天注册的，如果是，则读取用户绑定的主料
            if($type == 2 && $userInfo["engine"] == 0 && $game_detail["releasetime"] >= $userInfo_createStartTime){
                $game_detail_new = Db::name("game_user")
                ->field($colum . ", zodiac, number, stage_name, stage_no, type")
                ->where("uid = " . $uid)
                ->where("type = " . $type)
                ->where("area_type = " . $area_type)
                ->where("`release` = 1") //已发布状态
                ->order("stage_no desc")
                ->find();
                //如果今天绑定了数据，则覆盖当前数据，否则不覆盖
                if($game_detail_new){
                    $game_detail = $game_detail_new;
                }
            }
        }

        if(!$game_detail){
            $game_detail["detail"] = [];
            $game_detail["zodiac"] = [];
            $game_detail["number"] = [];
        }else{
            $game_detail["detail"] = json_decode($game_detail[$colum], true);
            unset($game_detail[$colum]);
            $game_detail["zodiac"] = explode(",", $game_detail["zodiac"]);
            $game_detail["number"] = explode(",", $game_detail["number"]);
            //处理数据长度
            foreach($game_detail["zodiac"] as &$val){
                if(is_numeric($val)){
                    $val = sprintf("%02d", $val);
                }
            }
            foreach($game_detail["number"] as &$val){
                if(is_numeric($val)){
                    $val = sprintf("%02d", $val);
                }
            }
            // foreach($game_detail["detail"] as &$val){
            //     if(isset($val["zodiac"]) && is_numeric($val["zodiac"])){
            //         $val["zodiac"] = sprintf("%02d", $val["zodiac"]);
            //     }
            //     if(isset($val["number"]) && is_numeric($val["number"])){
            //         $val["number"] = sprintf("%02d", $val["number"]);
            //     }
            // }
        }

        //倒序 期数
        $game_detail["game_stage_lists"] = $game_stage_ten;

        $this->success("操作成功", $game_detail);
        
    }

    public function test()
    {
        $game_lists = Db::name("game")
        ->where("type = 2")
        ->where("stage_no = 106")
        ->select();

        $user_lists = Db::name("user")
        ->field("id, createtime")
        ->select();

        foreach($game_lists as $game_val){
            //发布开始日期
            $releasetime_start = strtotime(Date("Y-m-d 00:00:00", $game_val["releasetime"]));
            //发布结束日期
            $releasetime_end = strtotime(Date("Y-m-d 23:59:59", $game_val["releasetime"]));
            foreach($user_lists as &$user_val){
                //查询当前用户是否已经有绑定数据
                $game_user_info = Db::name("game_user")
                ->where("uid = " . $user_val["id"])
                ->where("stage_no = " . $game_val["stage_no"])
                ->find();
                //用户不存在绑定数据，并且注册日期处于发布日期当天，则进行绑定
                if(!$game_user_info && $user_val["createtime"] >= $releasetime_start && $user_val["createtime"] <= $releasetime_end){
            
                    $insert_data = $game_val;
                    $insert_data["uid"] = $user_val["id"];
                    $insert_data["game_id"] = $game_val["id"];
                    unset($insert_data["id"]);
                    Db::name("game_user")->insert($insert_data);
                    
                }
                
            }
        }
        return "执行完毕";
    }
}
